import pClear from '@/static/searchClose.png';
import { Image, Input, View, Text } from '@tarojs/components';
import React, { useEffect, useState } from 'react';
import styles from './index.module.scss';

const noop = () => {};

const Search = ({
  className = '',

  defaultValue = '',
  value = '',
  onChange = noop,
  onConfirm = noop,

  showClear = true,
  onClear = noop,

  showBtn = false,
  btnTxt = '搜索',

  autoFocus,
  onFocus = noop,
  onBlur = noop,
  ...inputProps
}) => {
  const [focus, setFocus] = useState(autoFocus);
  const [searchValue, setSearchValue] = useState(defaultValue);

  const inputHandler = (e) => {
    const v = e.detail.value;

    setSearchValue(v);
    onChange(v);
  };

  const inputClear = () => {
    setSearchValue('');
    onChange('');
    onClear();

    setTimeout(() => {
      setFocus(true);
    }, 0);
  };

  // 外部传入更新
  useEffect(() => {
    setSearchValue(value);
  }, [value]);

  return (
    <View className={`${styles.Search} ${className}`}>
      <View className="left">
        <Text className="search-icon at-icon at-icon-search"></Text>

        <Input
          className="input"
          type="text"
          confirmType="search"
          placeholderClass="placeholder"
          value={searchValue}
          focus={focus}
          onConfirm={() => {
            onConfirm(searchValue);
          }}
          onInput={(e) => {
            inputHandler(e);
          }}
          onFocus={() => {
            onFocus();
            setFocus(true);
          }}
          onBlur={() => {
            onBlur();
            setFocus(false);
          }}
          {...inputProps}
        />

        {showClear && searchValue.length > 0 && (
          <View className="clear" onClick={inputClear}>
            <Image className="icon" src={pClear} />
          </View>
        )}
      </View>

      {showBtn && (
        <View
          className="right"
          onClick={() => {
            onConfirm(searchValue);
          }}
        >
          <View className="txt">{btnTxt}</View>
        </View>
      )}
    </View>
  );
};

export default Search;
